#include "stdafx.h"
#include "MultiLinePropertyHandler.h"

CMultiLinePropertyHandler::CMultiLinePropertyHandler(void) :
	m_bIsModified(FALSE)
{
}

CMultiLinePropertyHandler::~CMultiLinePropertyHandler(void)
{
}

CMultiLinePropertyHandler::CMultiLinePropertyHandler(LPCWSTR lpPropertyLine) :
	m_bIsModified(FALSE) //superfluous but make code more obvious
{
	Parse(lpPropertyLine);
}

void CMultiLinePropertyHandler::Parse(const CAtlStringW & strPropertyLine, wchar_t chDelimiter)
{
	m_aItems.RemoveAll();
	int nFind = -1, nPrev;
	CAtlStringW str;

	do
	{
		nPrev = nFind + 1;
		nFind = strPropertyLine.Find(chDelimiter, nPrev);
		if (-1 == nFind)
			str = strPropertyLine.Mid(nPrev);
		else
			str = strPropertyLine.Mid(nPrev, nFind - nPrev);

		if (str.GetLength())
			m_aItems.Add(str);
	}
	while (-1 != nFind);
	m_bIsModified = FALSE;
}

void CMultiLinePropertyHandler::Parse(const CAtlStringW & strPropertyLine, LPCWSTR lpDelimiter)
{
	m_aItems.RemoveAll();
	int nDelimiterLen = static_cast<int>(wcslen(lpDelimiter));
	int nFind = -nDelimiterLen, nPrev;
	CAtlStringW str;

	do
	{
		nPrev = nFind + nDelimiterLen;
		nFind = strPropertyLine.Find(lpDelimiter, nPrev);
		if (-1 == nFind)
			str = strPropertyLine.Mid(nPrev);
		else
			str = strPropertyLine.Mid(nPrev, nFind - nPrev);

		if (str.GetLength())
			m_aItems.Add(str);
	}
	while (-1 != nFind);
	m_bIsModified = FALSE;
}

BOOL CMultiLinePropertyHandler::IsDefined(LPCWSTR lpProperty) const
{
	//since thehe is not many items simple loop is enouph
	for(size_t t = 0; t < m_aItems.GetCount(); ++t)
	{
		if (m_aItems.GetAt(t) == lpProperty)
			return TRUE;
	}
	return FALSE;
}

void CMultiLinePropertyHandler::RemoveIfExist(LPCWSTR lpProperty)
{
	for(size_t t = 0; t < m_aItems.GetCount(); ++t)
	{
		if (m_aItems.GetAt(t) == lpProperty)
		{
			m_aItems.RemoveAt(t);
			m_bIsModified = TRUE;
			break;
		}
	}
}

void CMultiLinePropertyHandler::Add(LPCWSTR lpProperty)
{
	if (FALSE == IsDefined(lpProperty))
	{
		m_aItems.Add(lpProperty);
		m_bIsModified = TRUE;
	}
}

void CMultiLinePropertyHandler::GetPropertyLine(CAtlStringW & str, wchar_t chDelimiter) const
{
	str.Empty();

	if (m_aItems.GetCount() == 0)
		return;

	str = m_aItems.GetAt(0);
	for(size_t t = 1; t < m_aItems.GetCount(); ++t)
	{
		str.AppendChar(chDelimiter);
		str.Append(m_aItems.GetAt(t));
	}
}

void CMultiLinePropertyHandler::GetPropertyLine(CAtlStringW & str, LPCWSTR lpDelimiter) const
{
	str.Empty();

	if (m_aItems.GetCount() == 0)
		return;

	str = m_aItems.GetAt(0);
	for(size_t t = 1; t < m_aItems.GetCount(); ++t)
	{
		str.Append(lpDelimiter);
		str.Append(m_aItems.GetAt(t));
	}
}

void CMultiLinePropertyHandler::SetAt(size_t nIndex, const CAtlStringW & wstrValue)
{
	m_bIsModified = TRUE;
	m_aItems.SetAt(nIndex, wstrValue);
}

